class_name Interactable
extends Area2D

@export var disabled := false
@export var auto_activate := false

var action: Callable
@onready var polygon_2d: Polygon2D = $Polygon2D


func init_interactable() -> void:
	pass


func _ready() -> void:
	body_entered.connect(_on_body_entered)
	body_exited.connect(_on_body_exited)
	%Player.interact.connect(_on_interact)
	collision_layer = 0
	collision_mask = 0
	set_collision_mask_value(3, true)
	init_interactable()


func _on_body_entered(_body: Node2D) -> void:
	GlobalGameData.player_interacting_with.append(name)
	if auto_activate: _on_interact()


func _on_body_exited(_body: Node2D) -> void:
	GlobalGameData.player_interacting_with.erase(name)


func _on_interact() -> void:
	if !GlobalGameData.player_interacting_with:
		return
	if GlobalGameData.player_interacting_with.back() != name or disabled:
		return
	if action:
		action.call()


func _process(_delta: float) -> void:
	if polygon_2d:
		if !GlobalGameData.player_interacting_with:
			polygon_2d.hide()
			return
		if GlobalGameData.player_interacting_with.back() != name or disabled: polygon_2d.hide()
		else: polygon_2d.show()
